<template>
  <div class="sign-page">
    <div class="login">
      <div class="header">
        <div class="switch-btn" :class="{'active': tabIndex == 1}" @click="tabIndex = 1">密码登录</div>
        <div class="switch-btn" :class="{'active': tabIndex == 2}" @click="tabIndex = 2">短信快捷登录</div>
      </div>
      <div class="body">
        <!-- 密码登录 -->
        <el-form class="v-form"  v-if="tabIndex == 1" :model="pawdForm" ref="pawdForm" :rules="pawdFormRules">
          <el-form-item class="v-form-item pre-icon " prop="mobile">
            <i class="icon-mobile"></i>
            <el-input v-model="pawdForm.mobile" size="medium" placeholder="请输入手机号码" maxlength="11" clearable></el-input>
          </el-form-item>
          <el-form-item class="v-form-item pre-icon " prop="password">
            <i class="icon-lock"></i>
            <el-input v-model="pawdForm.password" size="medium" type="password" placeholder="请输入密码" maxlength="20" @keyup.enter.native="login" clearable></el-input>
          </el-form-item>
        </el-form>
        <!-- 短信快捷登录 -->
        <el-form class="v-form"  v-if="tabIndex == 2" :model="smsForm" ref="smsForm" :rules="smsFormRules">
          <el-form-item class="v-form-item pre-icon" prop="mobile">
            <i class="icon-mobile"></i>
            <el-input v-model="smsForm.mobile" size="medium" placeholder="请输入手机号码" maxlength="11" clearable></el-input>
          </el-form-item>
          <el-form-item class="v-form-item" prop="imgCode">
            <el-input v-model="smsForm.imgCode" size="medium" placeholder="请输入图片验证码" maxlength="4" @blur="checkImgCode" clearable>
              <template slot="append">
                <img :src="imgCodeSrc" class="image-code" @click="getImgCode">
              </template>
            </el-input>
            <p class="v-valid-tips success" v-show="isImgCodeRight">验证码输入正确</p>
          </el-form-item>
          <el-form-item class="v-form-item" prop="msgCode">
            <el-input v-model="smsForm.msgCode" size="medium" placeholder="请输入短信验证码" maxlength="6" @keyup.enter.native="login" clearable>
              <template slot="append">
                <button type="button" class="inner-btn" :class="{'disabled': sendMsg}" :disabled="sendMsg" @click="sendMsgCode">{{msgTip}}</button>
              </template>
            </el-input>
          </el-form-item>
        </el-form>
        <!-- 登录按钮 -->
        <div class="login-btn" @click="login">登录</div>
        <div class="bottom">
          <router-link class="link-btn fl" to="/login/passwordReset">忘记密码</router-link>
          <router-link class="link-btn fr" to="/signup">立即注册</router-link>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import Md5 from 'js-md5'
import {mapActions} from 'vuex'

export default {
  data () {
    return {
      tabIndex: 1, // 登录类型： 1: 密码； 2:短信。
      pawdForm: { // 密码登录
        type: 1,
        mobile: '',
        password: ''
      },
      pawdFormRules: {
        mobile: [
          {required: true, message: '请输入手机号码', trigger: 'blur'},
          {
            validator: (rule, value, callback) => {
              if (value.trim() === '') {
                callback(new Error('请输入手机号码'))
              } else if (!(/^1[3456789]\d{9}$/.test(value))) {
                callback(new Error('您输入手机号码不正确'))
              } else {
                callback()
              }
            },
            trigger: 'change'
          }
        ],
        password: [
          {required: true, message: '请输入密码', trigger: 'blur'},
          {
            validator: (rule, value, callback) => {
              if (value.length < 6) {
                callback(new Error('密码应不少于6个字符'))
              } else if (!/^[0-9a-zA-z]+$/.test(value)) {
                callback(new Error('密码必须由数字和字母组成'))
              } else {
                callback()
              }
            },
            trigger: 'change'
          }
        ]
      },
      smsForm: { // 短信快捷登录
        type: 2,
        operateType: 'login',
        mobile: '',
        imgCode: '',
        msgCode: ''
      },
      smsFormRules: {
        mobile: [
          {required: true, message: '请输入手机号码', trigger: 'blur'},
          {
            validator: (rule, value, callback) => {
              if (value.trim() === '') {
                callback(new Error('请输入手机号码'))
              } else if (!(/^1[3456789]\d{9}$/.test(value))) {
                callback(new Error('您输入手机号码不正确'))
              } else {
                callback()
              }
            },
            trigger: 'change'
          }
        ],
        imgCode: [
          {required: true, message: '请输入图片验证码', trigger: 'blur'},
          {
            validator: (rule, value, callback) => {
              if (!/^[a-zA-z0-9]{4}$/.test(value)) {
                callback(new Error('图片验证码有误，请重新输入'))
              } else {
                callback()
              }
            },
            trigger: 'change'
          }
        ],
        msgCode: [
          {required: true, message: '请输入短信验证码', trigger: 'blur'},
          {
            validator: (rule, value, callback) => {
              if (!/^[a-zA-z0-9]{6}$/.test(value)) {
                callback(new Error('短信验证码有误，请重新输入'))
              } else {
                callback()
              }
            },
            trigger: 'change'
          }
        ]
      },
      imgCodeSrc: this.$api + '/pc/sys/verify', // 图片验证码
      isImgCodeRight: false, // 图片验证码是否正确
      sendMsg: false, // 是否已发送短信验证码
      msgTip: '获取验证码', // 获取短信验证码提示语
      time: 0, // 重新获取验证码时间，单位: s
      disabled: false
    }
  },
  mounted () {
    this.$store.commit('setHeaderTit', '登录')
  },
  methods: {
    ...mapActions({
      loginByPSW: 'user/loginByPSW',
      loginBySMS: 'user/loginBySMS'
    }),
    login () {
      if (!this.disabled) {
        this.disabled = true
        if (this.tabIndex === 1) {
          this.$refs.pawdForm.validate(valid => {
            if (valid) {
              let formData = this.pawdForm
              formData.password = Md5(this.pawdForm.password)
              this.loginByPSW(formData).then(() => {
                this.$store.dispatch('shopcart/getShopcart')
              })
            } else {
              return false
            }
          })
        } else {
          this.$refs.smsForm.validate(valid => {
            if (valid) {
              this.loginBySMS(this.smsForm).then(() => {
                this.$store.dispatch('shopcart/getShopcart')
              })
            } else {
              return false
            }
          })
        }
      }
      setTimeout(() => {
        this.disabled = false
      }, 2000)
    },
    // 获取图片验证码
    getImgCode () {
      let time = new Date()
      this.imgCodeSrc = this.$api + '/pc/sys/verify?time=' + Date.parse(time)
      this.isImgCodeRight = false
      if (this.$refs.smsForm) {
        this.$refs.smsForm.$children[1].resetField()
      }
    },
    // 检查图片验证码是否正确
    checkImgCode () {
      if (this.smsForm.imgCode) {
        this.$http.post(this.$api + '/pc/sys/checkImgCode', {
          imgCode: this.smsForm.imgCode
        }).then(res => {
          if (res.responseCode === '0000') {
            this.isImgCodeRight = true
          } else {
            this.isImgCodeRight = false
            this.$message.error({
              duration: this.$store.state.duration,
              message: res.responseMsg
            })
          }
        })
      } else {
        return false
      }
    },
    // 发送短信验证码
    sendMsgCode () {
      if (this.smsForm.mobile && this.isImgCodeRight && /^1[3456789]\d{9}$/.test(this.smsForm.mobile)) {
        this.$http.post(this.$api + '/pc/sys/sendMsg', {
          mobile: this.smsForm.mobile,
          operateType: this.smsForm.operateType
        }).then(res => {
          if (res.responseCode === '0000') {
            this.sendMsg = true
            this.$message({
              type: 'success',
              message: '验证码已发送，请注意查收'
            })
          } else {
            this.$message.error({
              duration: this.$store.state.duration,
              message: res.responseMsg
            })
          }
        })
      } else {
        this.$message.error('请输入正确的手机号码和图片验证码')
      }
    }
  },
  watch: {
    // 检测到登录类型改变时重置表单
    'tabIndex': function (val) {
      if (val === 1) {
        this.$nextTick(() => {
          this.$refs.pawdForm.resetFields()
        })
      } else {
        this.$nextTick(() => {
          this.isImgCodeRight = false
          this.$refs.smsForm.resetFields()
          this.smsForm.msgCode = ''
        })
      }
    },
    'smsForm.imgCode': function () {
      this.isImgCodeRight = false
    },
    // 检测到已发送短信验证码禁用发送按钮并开始倒计时
    'sendMsg': function () {
      if (this.sendMsg) {
        this.time = 60
      } else {
        return false
      }
    },
    // 短信验证码倒计时
    'time': function () {
      if (this.sendMsg) {
        if (this.time === 0) {
          this.sendMsg = false
          this.msgTip = '获取验证码'
        } else {
          setTimeout(() => {
            this.time--
            this.msgTip = '重新发送(' + this.time + ')'
          }, 1000)
        }
      } else {
        this.msgTip = '获取验证码'
      }
    }
  }
}
</script>

<style lang="scss" scoped>
@import '@/assets/scss/basic.scss';
.login {
  position: absolute;
  top: 80px;
  left: 50%;
  margin-left: 200px;
  width: 400px;
  background: #fff;
  box-shadow: 0 8px 15px rgba(0, 0, 0, 0.3);
  .header {
    height: 60px;
    font-size: 0;
    background: $bg_color;
    border-bottom: solid 1px $border_color;
    .switch-btn {
      position: relative;
      display: inline-block;
      width: 50%;
      font-size: $fz_18;
      color: $f_main;
      text-align: center;
      line-height: 60px;
      font-weight: 400;
      cursor: pointer;
      &:last-child::before {
        content: '';
        position: absolute;
        top: 20px;
        left: 0;
        width: 1px;
        height: 20px;
        background: $border_color;
      }
      &.active {
        color: $green;
      }
    }
  }
  .body {
    padding: 30px 40px;
    .login-btn {
      margin: 10px 0;
      width: 100%;
      height: 45px;
      line-height: 45px;
      font-size: $fz_16;
      text-align: center;
      letter-spacing: 0.5em;
      color: #ffffff;
      background: $green;
      cursor: pointer;
      transition: all 0.3s;
      &:hover {
        background: $green_l;
      }
    }
    .image-code {
      display: block;
      width: 99px;
      height: 34px;
      cursor: pointer;
    }
  }
  .bottom {
    overflow: hidden;
    .link-btn {
      font-size: $fz_14;
      color: $f_normal;
      &:hover {
        color: $green_d;
      }
    }
  }
}
</style>
